from src.core import log
import uuid, json, hashlib
from src.db import dbm, dbs
from typing import Dict, Any
from datetime import datetime
from sqlalchemy.orm import scoped_session
from src.core.variables.info import VERSION
from src.core.variables.constant import CONF
from base64 import urlsafe_b64encode, urlsafe_b64decode


# BUG 2025年10月16日 AAAAAA 错误 pypy安装cryptography时需要依赖rust工具链，当前0.7-beta版本将暂时去除多节点功能，保证原有功能正常


class Cert:
    def __init__(self) -> None:
        pass

    def create_certificate(self) -> Dict[str, Any]:
        """生成包含机器指纹的安全证书"""
        with dbm.get(f'sys_default') as db_session:
            db_session: scoped_session
            machine_info = {
                "ip": CONF.LOCAL_IP,
                "port": CONF.LOCAL_PORT,
                "node_id": db_session.query(dbs.sys_default.Node).filter(dbs.sys_default.Node.host == 'localhost').first().node_id,
                "timestamp": datetime.utcnow().isoformat(),
                "mb_id": self.__get_mb_id(),
                "salt": uuid.uuid4().hex[:8],
            }
            json_str = json.dumps(machine_info)
            # 使用base64编码替代加密
            encoded = urlsafe_b64encode(json_str.encode()).decode()
            result = {
                "data": encoded,
            }
            certificate_json = json.dumps(result)
            db_result = db_session.query(dbs.sys_default.Node).filter(dbs.sys_default.Node.host == 'localhost').first()
            if db_result:
                db_result.certificate = certificate_json
            else:
                log.CRITICAL(f'数据库中缺少本节点信息，请检查数据库！')
            if dbm.commit(db_session):
                log.INFO(f'生成本机绑定信息成功')                
        return result

    def analyze_certificate(self, certificate: str) -> dict:
        cert_data = json.loads(certificate) if isinstance(certificate, str) else certificate
        data = cert_data.get("data", None)
        # 使用base64解码替代解密
        decoded = urlsafe_b64decode(data.encode())
        return json.loads(decoded.decode())

    def __get_mb_id(self) -> str:
        """获取主板ID"""
        try:
            with open("/sys/class/dmi/id/product_uuid") as f:
                return f.read().strip()
        except:
            return str(uuid.getnode())

    def is_registered(self, registry: set) -> bool:
        """检查证书是否已注册"""
        return (
            hashlib.sha256(json.dumps(self.certificate["info"]).encode()).hexdigest()
            in registry
        )

    def is_same_version(self, target_version: str) -> bool:
        """版本一致性检查"""
        return target_version == VERSION

    def is_complete(self) -> bool:
        """基础完整性验证"""
        required_fields = {"ip", "timestamp", "mb_id", "salt"}
        return all(f in self.certificate.get("info", {}) for f in required_fields)

    def is_config_supported(self, config: dict) -> bool:
        """配置兼容性检查"""
        min_ver = config.get("min_supported_version", "0.0.0")
        return self.is_same_version(min_ver)